package models

import (
	"github.com/astaxie/beego/orm"
	"encoding/base64"
	"fmt"
)

type MassItem struct {
	Id     int    `orm:"column(id);auto" description:"ID"`
	TaskId int    `orm:"column(task_id)" description:"任务ID"`
	Title  string `orm:"column(title);size(255)" description:"标题"`
	Data   string `orm:"column(data);size(255)" description:"链接"`
}

type FormatMassItem struct {
	Sort    int
	AppName string
	MassItem
}

func (t *MassItem) TableName() string {
	return "mass_item"
}

func init() {
	orm.RegisterModel(new(MassItem))
}

func GetItemList(appName string, taskId, page, pageSize int) ([]*FormatMassItem, int64) {
	o := orm.NewOrm()
	offset := (page - 1) * pageSize
	cond := orm.NewCondition()
	cond = cond.And("task_id", taskId)
	massItems := make([]*MassItem, 0)
	query := o.QueryTable(TableName("mass_item"))
	query = query.SetCond(cond)
	total, _ := query.Count()
	query.OrderBy("id").Limit(pageSize, offset).All(&massItems)
	formatMassItems := make([]*FormatMassItem, 0)
	for k, v := range massItems {
		formatMassItem := &FormatMassItem{
			Sort:     k + 1,
			AppName:  appName,
			MassItem: *v,
		}
		title, _ := base64.StdEncoding.DecodeString(formatMassItem.Title)
		data := formatMassItem.Data
		formatMassItem.Title = string(title)
		formatMassItem.Data = string(data)
		formatMassItems = append(formatMassItems, formatMassItem)
	}

	return formatMassItems, total
}

func AddTaskItem(taskId int, tip, data string) error {
	o := orm.NewOrm()
	massItem := &MassItem{
		TaskId: taskId,
		Title:  base64.StdEncoding.EncodeToString([]byte(tip)),
		Data:   data,
	}
	_, err := o.Insert(massItem)
	if err != nil {
		fmt.Println("insert mass_item error", err)
		return err
	}
	return nil
}

func EditTaskItem(id int, title, data string) error {
	o := orm.NewOrm()
	massItem := &MassItem{Id:id}
	err := o.Read(massItem)
	if err != nil {
		fmt.Println("select mass_item error",err)
		return err
	}
	massItem.Title = base64.StdEncoding.EncodeToString([]byte(title))
	massItem.Data = data
	if _, err := o.Update(massItem); err != nil {
		fmt.Println("update mass_item error", err)
		return err
	}
	return nil
}

func DelTaskItem(id int) error{
	o := orm.NewOrm()
	if _, err := o.Delete(&MassItem{Id: id}); err != nil {
		fmt.Println("delete mass_item error", err)
		return err
	}
	return nil
}
